﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace PlaneClean.Filter
{
    public class CommonMessageHandler : DelegatingHandler
    {
        public static void setCorsHeader(HttpResponseHeaders res, HttpRequestMessage request)
        {
            res.Add("Access-Control-Allow-Origin", request.Headers.GetValues("Origin").FirstOrDefault());
            res.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");//允许跨域的请求方式
            res.Add("Access-Control-Max-Age", "3600");//预检请求的间隔时间
            res.Add("Access-Control-Allow-Headers", string.Join(",", "x-token, content-type"));
            //res.Headers.Add("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token,Access-Control-Allow-Headers");//允许跨域请求携带的请求头
            res.Add("Access-Control-Allow-Credentials", "true");//若要返回cookie、携带seesion等信息则将此项设置我true
        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            Task<HttpResponseMessage> taskResponse = base.SendAsync(request, cancellationToken);
            HttpStatusCode statusCode = taskResponse.Result.StatusCode;
            if (taskResponse.Result.StatusCode != HttpStatusCode.OK) taskResponse.Result.StatusCode = HttpStatusCode.OK;
            if (request.Method == HttpMethod.Options)
            {
                taskResponse.Result.Content = new StringContent("");
            }
            setCorsHeader(taskResponse.Result.Headers, request);
            return taskResponse;
        }
    }
}